# *-* coding:utf8 *-*
from info import db, constants
from info.models import Category, News, User
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu
from info.utils.common import user_login_data
from flask import render_template, g, request, jsonify, redirect, current_app, session, abort


@profile_blu.route('/info')
@user_login_data
def uget_user_info():
    user = g.user
    if not user:
        # 代表没有登录，重定向到首页
        return redirect("/")
    data = {"user_info": user.to_dict()}
    return render_template('news/user.html', data=data)


@profile_blu.route('/base_info',methods = ['POST','GET'])
@user_login_data
def base_info():
    '''用户的基本信息'''
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_base_info.html',data = {'user_info':user.to_dict()})

    json_data = request.json
    signature = json_data.get('signature')
    nick_name = json_data.get('nick_name')
    gender = json_data.get('gender')

    # 检验参数
    if not all([signature,nick_name,gender]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不足')

    if gender not in (['WOMAN','MAN']):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')

    user = g.user
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name

    return jsonify(errno = RET.OK,errmsg = 'OK')


@profile_blu.route('/pic_info',methods = ['GET','POST'])
@user_login_data
def pic_info():
    '''用户头像'''
    user = g.user
    if request.method == 'GET':

        return render_template('news/user_pic_info.html',data = {"user_info":user.to_dict()})

    # 获取上传的文件
    try:
        avatar_file = request.files.get("avatar").read()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '获取错误')


    # 文件上传到七牛云
    try:
        url = storage(avatar_file)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.THIRDERR,errmsg = '上传出错啦!!')

    user.avatar_url = url

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '保存失败')

    data ={'avatar_url':constants.QINIU_DOMIN_PREFIX + url}
    return jsonify(errno = RET.OK,errmsg = 'OK',data=data)

@profile_blu.route('/pass_info', methods = ['GET','POST'])
@user_login_data
def pass_info():
    '''修改密码'''
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    json_data = request.json
    old_password = json_data.get('old_password')
    new_password = json_data.get('new_password')

    if not all([old_password,new_password]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    user = g.user
    # 判断密码
    if not user.check_passowrd(old_password):
        return jsonify(errno = RET.PWDERR,errmsg = '原密码错误')

    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '保存错误!!!')

    return jsonify(errno = RET.OK,errmsg = 'OK')

@profile_blu.route('/collection')
@user_login_data
def collection_user():
    # 获取页数
    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    collection = list()
    current_page = 1
    total_page = 1

    try:
        # 进行分页查询
        paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取分页
        collection = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页
        total_page = paginate.pages
    except Exception as e:
        current_page.logger.error(e)

    # 查询收藏
    collection_dict_li = list()
    for collections in collection:
        collection_dict_li.append(collections.to_basic_dict())

    data = {
        'current_page':current_page,
        'total_page':total_page,
        'collections':collection_dict_li
    }

    return render_template('news/user_collection.html',data = data)


@profile_blu.route('/news_release',methods=['GET','POST'])
@user_login_data
def news_relwase():
    '''新闻发布'''
    if request.method == 'GET':
        # 获取新闻的分类
        category = list()
        try:
            categorys = Category.query.all()

        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR,errmsg = '获取分类失败')

        # 接收分类数据
        categories_dicts = list()

        for category_li in categorys:
            # 接收
            catelist = category_li.to_dict()
            # 拼接
            categories_dicts.append(catelist)

        categories_dicts.pop(0)

        return render_template('news/user_news_release.html',data={"categories": categories_dicts})
    # 获取要提交的数据
    """新闻发布:
        接收参数:title	string 新闻标题
                category_id	int 新闻分类_id
                digest	string	新闻摘要
                index_image	file 索引图片
                content	string	新闻内容
        格式:json

    """
    # None
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([title,source,category_id,digest,index_image,content]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    # 读取图片
    try:
        index_image = index_image.read()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '参数有误!!')

    # 上传到七牛云
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.THIRDERR,errmsg = '上传失败')

    # 初始化模型
    news = News()
    news.title = title
    news.source = source
    news.content = content
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.user_id = g.user.id
    news.category_id = category_id

    # 模拟等待审核
    news.status = 0

    # 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR,errmsg = '保存失败')

    return jsonify(errno = RET.OK,errmsg = 'OK')


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    # 获取页数
    p = request.args.get('p',1)
    try:

        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页查询
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = list()

    for new_item in news_li:
        news_dict_li.append(new_item.to_review_dict())
    data = {'news_list':news_dict_li,'current_page':current_page,'total_page':total_page}

    return render_template('news/user_news_list.html',data = data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    '''我的关注'''

    p = request.args.get('p', 1)
    try:

       p = int(p)
    except Exception as e:
       current_app.logger.error(e)
       p = 1

    user = g.user
    follows = []
    current_page = 1
    total_page = 1
    try:
       # 进行分页查询
       paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
       # 获取分页
       follows = paginate.items
       # 获取当前页
       current_page = paginate.page
       # 获取总页
       total_page = paginate.pages
    except Exception as e:
       current_app.logger.error(e)

    user_dict_li = []
    for itme in follows:
        user_dict_li.append(itme.to_dict())

    data = {"users": user_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_follow.html',data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    '''查看其他用户信息'''
    user = g.user

    user_id = request.args.get('id')
    if not user_id:
        abort(404)
    # 获取他人id
    other = None

    try:
        other = User.query.get(user_id)

    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 判断用户是否关注
    is_followed = False

    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True


    data = {
        'other_info':other.to_dict(),
        'is_followed':is_followed,
        'user_info':user.to_dict()
    }

    return render_template('news/other.html',data = data)

@profile_blu.route('/other_news_list')
@user_login_data
def otger_news_list():
    '''查看他人新闻列表'''
    p = request.args.get('p',1)
    user_id = request.args.get('user_id')

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误!!')

    if not all([p,user_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    try:
        user = User.query.get(user_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询错误')

    if not user:
        return jsonify(errno = RET.NODATA,errmsg = '用户不存在')

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p,constants.OTHER_NEWS_PAGE_MAX_COUNT,False)

        news_li = paginate.items

        current_page = paginate.page

        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '数据库查询错误')

    news_dict_li = list()
    for item in news_li:
        news_dict_li.append(item.to_review_dict())

    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}

    jsonify(errno = RET.OK,errmsg = 'OK',data = data)